<template>
  <Modal
      :draggable="!this.$config.mask"
      :mask="this.$config.mask"
      :mask-closable="!this.$config.mask"
      :value="value"
      @on-ok="save"
      @on-visible-change="visibleChange"
      :width="1000">
    <p slot="header">
      <template v-if="modalData.info.allot==='RUNNINGUSER'">
        选择下一步执行用户
      </template>
      <template v-if="modalData.info.allot==='RUNNINGROLE'">
        选择下一步执行角色
      </template>
    </p>
    <Form ref="allotForm" :model="allot" label-position="top" :rules="allotRule">

      <FormItem label="指定用户" prop="userText" v-if="modalData.info.allot==='RUNNINGUSER'">
        <Input v-model="allot.userText" readonly placeholder="" @on-focus="focusUser" ref="userText" clearable @on-clear="clearRunningUser"></Input>
      </FormItem>
      <FormItem label="指定角色" prop="roleText" v-if="modalData.info.allot==='RUNNINGROLE'">
        <Input v-model="allot.roleText" readonly placeholder="" @on-focus="focusRole" ref="roleText" clearable @on-clear="clearRunningRole"></Input>
      </FormItem>

      <FormItem label="多人审批" prop="joinType">
        <Select v-model="allot.joinType" style="width:100%" @on-open-change="clearFocus" ref="joinType"
                placeholder="请选择多人审批方式" :disabled="modalData.info.allot==='RUNNINGUSER' && allot.users.length<=1">
          <Option v-for="item in joinTypes" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
      </FormItem>
      <FormItem :label="modalData.info.allot==='RUNNINGUSER'?'下一步执行用户是否可以抄送':'下一步执行角色是否可以抄送'" prop="copy">
        <i-switch v-model="allot.copy" @on-change="changeCopy"></i-switch>
      </FormItem>
      <FormItem label="抄送用户" prop="copyUserText">
        <Input v-model="allot.copyUserText" readonly placeholder="" ref="copyUserText"
               @on-focus="focusCopyUser" :disabled="!allot.copy" clearable @on-clear="clearCopyUser"></Input>
      </FormItem>

    </Form>
    <div slot="footer">
      <Button icon="md-close" @click="cancel">取消</Button>
      <Button icon="md-checkmark" type="primary" @click="save">确定</Button>
    </div>
    <o-u-user-select-modal v-if="userSelectModalMount1" v-model="userSelectModalShow1"
                           @submit="obtainOUUsers" :modal-data="userSelectModalData1"></o-u-user-select-modal>
    <role-select-modal v-if="roleSelectModalMount" v-model="roleSelectModalShow"
                       @submit="obtainRoles" :modal-data="roleSelectModalData"></role-select-modal>
    <user-select-modal v-if="userSelectModalMount2" v-model="userSelectModalShow2"
                       @submit="obtainUsers" :modal-data="userSelectModalData2"></user-select-modal>
  </Modal>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import _ from 'lodash';
import FlowInstance from '@/store/entities/flow/flow-instance/flow-instance';
import OUUserSelectModal from '@/components/common-modal/o-u-user-select-modal.vue';
import RoleSelectModal from '@/components/common-modal/role-select-modal.vue';
import Allot from '@/store/entities/flow/flow-instance/allot';
import AllotWithInstanceId from '@/store/entities/flow/flow-instance/allot-with-instance-id';
import UserSelectModal from '@/components/common-modal/user-select-modal.vue';

@Component({
  components: {UserSelectModal, OUUserSelectModal, RoleSelectModal},
})
export default class AllotModal extends AbpBase {
  name: string = 'AllotModal';
  @Prop({type: Boolean, default: false}) value: boolean;
  @Prop({type: Object, default: {}}) modalData: any;
  @Prop({type: String, default: ''}) type: string;
  allot: Allot = new Allot();
  allotRule = {
    userText: [
      {
        validator: (rule, value, callback) => {
          if((this.$refs.userText as any).value===''){
            console.log((this.$refs.userText as any).value);
            callback(new Error('指定下一步执行用户是必须的'));
          } else {
            callback();
          }

        },
        trigger: 'blur,change',
        required: true,
      },
    ],
    roleText: [
      {
        validator: (rule, value, callback) => {
          if((this.$refs.roleText as any).value===''){
            callback(new Error('指定下一步执行角色是必须的'));
          } else {
            callback();
          }

        },
        trigger: 'blur,change',
        required: true,
      },
    ],
    joinType: [
      {
        validator: (rule, value, callback) => {
          if ((this.$refs.joinType as any).disabled) {
            callback();
          } else {
            if((this.$refs.joinType as any).value===''){
              callback(new Error('请选择多人审批方式'));
            } else {
              callback();
            }
          }
        },
        trigger: 'blur,change',
        required: true,
      },
    ],
    copyUserText: [
      {
        validator: (rule, value, callback) => {
          if ((this.$refs.copyUserText as any).disabled) {
            callback();
          } else {
            if((this.$refs.copyUserText as any).value===''){
              callback(new Error('允许抄送情况下，指定抄送用户是必须的'));
            } else {
              callback();
            }
          }
        },
        trigger: 'blur,change',
        required: true,
      },
    ],

  };
  joinTypes = [
    {
      value: 'ALL',
      label: '会签（所有审批人都处理才行）',
    }, {
      value: 'ANY',
      label: '或签（任一审批人处理后即可）',
    },
  ];
  userSelectModalMount1: boolean = false;
  userSelectModalShow1: boolean = false;
  userSelectModalData1: any = {};

  userSelectModalMount2: boolean = false;
  userSelectModalShow2: boolean = false;
  userSelectModalData2: any = {};

  roleSelectModalMount: boolean = false;
  roleSelectModalShow: boolean = false;
  roleSelectModalData: any = {};

  visibleChange(value: boolean) {
    if (!value) {
      this.reset();
      this.$emit('input', value);
    }
  }

  cancel() {
    this.$emit('input', false);
  }

  save() {
    (this.$refs.allotForm as any).validate(async (valid: boolean) => {
      if (valid) {
        if (this.type === 'insert') {
          const instance = _.assign(new FlowInstance(), this.modalData.instance, this.allot);
          instance.allot = this.modalData.info.allot;
          await this.$store.dispatch({
            type: 'flowInstance/createOrUpdateFlowInstance',
            data: {
              flowInstance: instance
            }
          });
        }
        if (this.type === 'detail') {
          const verify = Object.assign(new AllotWithInstanceId(), this.modalData.instance, this.allot);
          verify.allot = this.modalData.info.allot;
          await this.$store.dispatch({
            type: 'flowInstance/verifyNode',
            data: verify,
          });
        }
        if (this.type === 'restart') {
          const restart = Object.assign(new FlowInstance(), this.modalData.instance, this.allot);
          restart.allot = this.modalData.info.allot;
          await this.$store.dispatch({
            type: 'flowInstance/restartFlowInstance',
            data: {
              flowInstance: restart,
            }
          });
        }
        this.$emit('on-submit', true, this.modalData.instance);
        this.$emit('input', false);
      }
    });
  }

  changeCopy(value: boolean) {
    if (!value) {
      this.allot.copyUsers = [];
      this.allot.copyUserText = '';
      this.$nextTick(() => {
        (this.$refs.allotForm as any).validateField('copyUserText');
      });

    }
  }

  focusUser() {
    const users = _.cloneDeep(this.allot.wholeUsers);
    if (this.modalData.info.sameUnit || this.modalData.info.restrictRoles.length > 0) {
      this.userSelectModalData2 = {selectedUsers: users, opener: 3,additional:{sameUnit:this.modalData.info.sameUnit,restrictRoles:this.modalData.info.restrictRoles,creator:this.modalData.creator}};
      this.userSelectModalMount2 = true;
      this.$nextTick(() => {
        this.userSelectModalShow2 = true;
      });
    } else {
      this.userSelectModalData1 = {selectedUsers: users, opener: 1};
      this.userSelectModalMount1 = true;
      this.$nextTick(() => {
        this.userSelectModalShow1 = true;
      });
    }
  }

  focusCopyUser() {
    const users = _.cloneDeep(this.allot.wholeCopyUsers);
    this.userSelectModalData1 = {selectedUsers: users, opener: 2};
    this.userSelectModalMount1 = true;
    this.$nextTick(() => {
      this.userSelectModalShow1 = true;
    });
  }

  focusRole() {
    const roles = _.cloneDeep(this.allot.wholeRoles);

    this.roleSelectModalData = {selectedRoles: roles, additional:{restrictRoles:this.modalData.info.restrictRoles}};
    this.roleSelectModalMount = true;
    this.$nextTick(() => {
      this.roleSelectModalShow = true;
    });
  }

  obtainOUUsers(selectedUsers: any, opener: number) {
    switch (opener) {
      case 1:
        this.allot.wholeUsers = selectedUsers;
        this.allot.users = this.allot.wholeUsers.map(u => u.id);
        this.allot.userText = selectedUsers.map(u => u.name).join(', ');
        if (this.allot.wholeUsers.length <= 1) {
          this.allot.joinType = '';
        }
        break;
      case 2:
        this.allot.wholeCopyUsers = selectedUsers;
        this.allot.copyUsers = this.allot.wholeCopyUsers.map(u => u.id);
        this.allot.copyUserText = selectedUsers.map(u => u.name).join(', ');
        break;
    }
    this.$nextTick(()=>{
      (this.$refs.allotForm as any).validateField('userText');
    });
  }

  obtainRoles(selectedRoles: any) {
    this.allot.wholeRoles = selectedRoles;
    this.allot.roles = this.allot.wholeRoles.map(r => r.id);
    this.allot.roleText = selectedRoles.map(r => r.displayName).join(', ');
    this.$nextTick(()=>{
      (this.$refs.allotForm as any).validateField('roleText');
    });
  }

  obtainUsers(selectedUsers: any) {
    this.allot.wholeUsers = selectedUsers;
    this.allot.users = this.allot.wholeUsers.map(u => u.id);
    this.allot.userText = selectedUsers.map(u => u.name).join(', ');
    if (this.allot.wholeUsers.length <= 1) {
      this.allot.joinType = '';
    }
    this.$nextTick(()=>{
      (this.$refs.allotForm as any).validateField('userText');
    });

  }

  clearFocus(value: boolean) {
    for (const element of this.$el.getElementsByClassName('ivu-select-item')) {
      element.classList.remove('ivu-select-item-focus');
    }
  }

  clearRunningUser(){
    this.allot.userText='';
    this.allot.users=[];
    this.allot.wholeUsers=[];
  }

  clearRunningRole(){
    this.allot.roleText='';
    this.allot.roles=[];
    this.allot.wholeRoles=[];
  }

  clearCopyUser(){
    this.allot.copyUserText='';
    this.allot.copyUsers=[];
    this.allot.wholeCopyUsers=[];
  }

  reset() {
    (this.$refs.allotForm as any).resetFields();
    this.allot = new Allot();
  }


  created() {

  }
}
</script>

<style lang="less" scoped>

</style>
